package com.feng.controller;
import com.feng.mapper.UserMapper;
import com.feng.pojo.User;
import com.feng.util.SetEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

// 所有写的请求前面加上/user便于区分
@Controller
public class UserController {
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    private UserMapper userMapper;

    // 跳转到登陆页面
    @GetMapping("/touser/login")
    public String toLogin(){
        return "user/login";
    }
    /**
     *   登陆验证
     */
    @RequestMapping("/user/login")
    public String login( String name, String password,
                        Model model, HttpSession session) {
        List<User> users = userMapper.selectList(null);
        boolean islogin = false;
        for (User user : users) {
            if (user.getName().equals(name) && user.getPassword().equals(password)) {
                // 登陆成功,防止表单重复提交，可以重定向到主页
                session.setAttribute("loginUser", user);
                islogin = true;
                break;
            }
        }

        if (islogin){
            return "user/index";
        }else{
            model.addAttribute("msg", "账号或密码错误");
            return "user/login";
        }

    }




    /**
     * 注册
     */
    @GetMapping("/user/adduser")
    public String addUser_get (){
        return "/user/reg";
    }

    @PostMapping("/user/adduser")
    public String addUser_post(User user,HttpSession session,String code){
        System.out.println(code);
        System.out.println(session.getAttribute("yanzhen"));
        if (code.equals(session.getAttribute("yanzhen"))){
            System.out.println(true);
            userMapper.insert(user);
            return "/user/login";
        }

        return "/user/reg";


    }


    // 发送邮箱
    @GetMapping("/user/setemail")
    @ResponseBody
    public boolean setemail(String email,HttpSession session) {
        System.out.println(email);
        String yanzhen = String.format("%04d", new Random().nextInt(9999));
        session.setAttribute("yanzhen", yanzhen);
        SetEmail setEmail = new SetEmail();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        setEmail.setEmail(email, yanzhen, mailSender);
                    }
                }
        ).start();
//        session.getAttribute("yanzhen");
        return true;
//        setEmail.setEmail(email,yanzhen,mailSender);


    }


}
